<?php

namespace App\Services\Goods\Traits;

use Illuminate\Support\Facades\DB;

trait UpdateCate
{
	/**
	 * @author:      李颖
	 * @DateTime:    2017-07-25 16:16:28
	 * @Description: 编辑分类
	 * 1、修改子类或无子类的父类->直接修改
	 * 2、修改拥有子类的父类->修改父类 + 修改子类的other_app_read
	 */
	private function _updateCate(string $logicPath, string $modelPath, array $data, string $getDbListMethod = 'dbCateList', string $getDbOneMethod = 'dbCateInfo'): array 
	{
		$logic = new $logicPath;

		$_where['id'] = $data['id'];
        //$_where['status'] = ['neq', -1];
        $_where = $logic->_addAppId($_where, $data['app_id']);

        $oneInfo = $logic->$getDbOneMethod($_where);
        
        $list = $logic->$getDbListMethod();
        $childs = child_ids($list, $data['id'], 'id', 'pid', 'id');
        if(count($childs) && isset($data['other_app_read']) && $oneInfo['other_app_read'] != $data['other_app_read']){
            DB::beginTransaction();
            try{

                $updateCateRes = (new $modelPath)->where($_where)->update($data);
                if(!$updateCateRes){ 
                    return auto_failure(null, '修改本顶级分类错误'); 
                }

                $_childWhere['id'] = ['in', $childs];
               // $_childWhere['status'] = ['neq', -1];
                $_childWhere = $logic->_addAppId($_childWhere, $data['app_id']);
                unset($_childWhere['id']);
                $childsData['other_app_read'] = $data['other_app_read'];
                $updateChilds = (new $modelPath)->where("status","<>",-1)->whereIn('id', $childs)->where($_childWhere)->update($childsData);
                if(!$updateChilds){
                    return auto_failure(null, '修改本顶级分类下的所有子类错误');
                }
                DB::commit();
                return auto_success($updateCateRes, '修改分类成功');

            }catch(\Exception $e){
                DB::rollBack();
                return auto_failure(null, '操作失败');
            }
            
        }else{
            //修改无子类的父类或子类
            unset($data['id']);
            $res = (new $modelPath)->where('status', '<>', -1)->where($_where)->update($data);
            return auto_return($res, '修改分类成功', '修改分类失败');
        }
	}
}